/*
 * @Descripttion: 
 * @version: 
 * @Author: TT
 * @Date: 2023-10-20 17:31:20
 * @LastEditors: TT-hzy 
 * @LastEditTime: 2024-05-22 15:16:24
 */

import '../config/config_index.dart';

import '../controllers/user_c.dart';
import 'dio_cache_tool.dart';
import 'getx_util_tool.dart';
import 'utils.dart';
import 'package:dio/dio.dart' as fdata;

enum Method {
  get,
  post,
}

/*
 * @description: 通用网络请求器
 * @params {
 *            path: 请求接口地址.
 *                  可以是url + path
 *                  也可以 path.但要设置baseurl.才可以正常使用,否者会404.
 *            data: 请求参数
 *          method: 请求方式.默认get
 *  isglobalparams: 是否需要全局参数.默认是true
 *                  这里我简单说一下,什么时候全局参数.一般我们后台接口,会添加一些通用参数.
 *                  比如客户端类型.(iOS,android,h5)等等.这样话,可能就需要大部分接口都
 *                  需要这样的参数.所以为了满足这个需求,我在封装这个请求器的时候,
 *                  就添加了这个参数.
 *    globalparams: 这个就是你要配置全局参数
 *                  你在请求器的方法里写死也可以.或者某些场景需要修改默认参数.这里也是支持的.
 *        showload: 显示默认加载loading.默认是true
 *         loadmsg: 加载动画提示文字.默认 加载中...
 * httpTransformer: 拦截器
 *          policy: 缓存策略
 *                    enum CachePolicy {
                      /// Same as [CachePolicy.request] when origin server has no cache config.
                      ///
                      /// In short, you'll save every successful GET requests.
                      forceCache,

                      /// Same as [CachePolicy.refresh] when origin server has no cache config.
                      refreshForceCache,

                      /// Requests and skips cache save even if
                      /// response has cache directives.
                      noCache,

                      /// Requests regardless cache availability.
                      /// Caches if response has cache directives.
                      refresh,

                      /// Returns the cached value if available (and un-expired).
                      ///
                      /// Checks against origin server otherwise and updates cache freshness
                      /// with returned headers when validation is needed.
                      ///
                      /// Requests otherwise and caches if response has directives.
                      request,
}
 * }
 * @return {网络数据}
 *  
*/
Future<HzyNormalResponse> request({
  required String path,
  dynamic data,
  Method method = Method.post,
  bool isShowLoad = true,
  bool isShowError = true,
  bool isneedglobalparams = true,
  Map<String, dynamic>? globalparams,
  String loadmsg = "Loading...",
  HzyNormalTransFormer? httpTransformer,
  CachePolicy policy = CachePolicy.request,
  Options? options,
  bool isFormData = true,
}) async {
  HzyNormalResponse res;
  if (isShowLoad) {
    showNormalLoadMsg(
      msg: loadmsg,
    );
  }
  Map<String, dynamic> params = {};
  if (isneedglobalparams) {
    globalparams ??= {};
    params.addAll(globalparams);
  }
  if (data is! fdata.FormData) {
    params.addAll(data ?? {});
  }

  options ??= DioCacheTool.cacheOptions
      ?.copyWith(
        policy: policy,
        keyBuilder: (request) {
          String keyB = data.toString();
          keyB = "$path$keyB";
          return keyB;
        },
      )
      .toOptions();
  if (method == Method.get) {
    res = await defaultClient().get(
      url: path,
      queryParameters: params,
      httpTransformer: httpTransformer,
      options: options,
    );
  } else {
    res = await defaultClient().post(
      path,
      data: isFormData ? fdata.FormData.fromMap(data ?? {}) : params,
      httpTransformer: httpTransformer,
      options: options,
    );
  }

  if (isShowLoad) {
    loadDismiss();
  }
  if (res.ok == false && res.error?.msg == "Please login!") {
    showToastMsg(
      res.error?.msg ?? "",
      onTap: () {
        UserC.current.logOut();
        currentTo(
          name: PageIdConfig.login,
        );
      },
    );
  } else if (isShowError && res.ok == false) {
    showToastMsg(res.error?.msg ?? "NetWork Fail");
  }
  return res;
}
